﻿/* Copyright (c) 2010 EPiServer AB
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
 * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Net.Mail;
using System.Text;
using System.Web;
using EPiServer.Configuration;
using EPiServer.Core;
using EPiServer.Municipality.Configuration;

namespace EPiServer.Municipality.Web.Mail {
    /// <summary>
    /// 
    /// </summary>
    /// <remarks></remarks>
    /// <example></example>
    public class MailUtil {
        /* *******************************************************************
        *  Public methods 
        * *******************************************************************/
        #region public static void SendHtmlMail(string subject, string body, string toEmail, string fromEmail)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="toEmail"></param>
        /// <param name="fromEmail"></param>
        public static void SendHtmlMail(string subject, string body, string toEmail, string fromEmail) {
            var message = new MailMessage(fromEmail, toEmail) { IsBodyHtml = true };
            var mailBody = new StringBuilder();
            AddHtmlMailHeader(subject, mailBody);
            mailBody.Append("<body>");
            mailBody.Append(body);
            mailBody.Append("</body></html>");
            message.Body = mailBody.ToString();
            message.Subject = subject;
            var smtpClient = new SmtpClient { UseDefaultCredentials = true };
            smtpClient.Send(message);
        }
        #endregion
        #region public static string GeneratePageUrl(PageData page)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public static string GeneratePageUrl(PageData page) {
            return GeneratePageUrl(page, string.Empty, string.Empty);
        }
        #endregion
        #region public static string GeneratePageUrl(PageData page, string queryStringName, string queryStringValue)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <param name="queryStringName"></param>
        /// <param name="queryStringValue"></param>
        /// <returns></returns>
        public static string GeneratePageUrl(PageData page, string queryStringName, string queryStringValue) {
            string pageUrl = null;
            if (((page.LinkURL != null) && page.LinkURL.StartsWith("/")) && !page.LinkURL.StartsWith("//")) {
                var startPage = PageReference.StartPage;
                var siteUrl = Settings.Instance.SiteUrl;
                var settingsFromPage = DataFactory.Instance.GetSettingsFromPage(page.PageLink);
                if (settingsFromPage.PageStartId != startPage.ID) {
                    siteUrl = settingsFromPage.SiteUrl;
                }
                pageUrl = siteUrl.GetLeftPart(UriPartial.Authority);
            }

            var tempUrl = UriSupport.AddLanguageSelection(page.LinkURL, page.LanguageBranch);
            if (queryStringName != string.Empty && queryStringValue != string.Empty) {
                tempUrl = UriSupport.AddQueryString(tempUrl, queryStringName, queryStringValue);
            }

            var url = new UrlBuilder(tempUrl);
            EPiServer.Global.UrlRewriteProvider.ConvertToExternal(url, page.PageLink, Encoding.UTF8);
            pageUrl += url.ToString();

            return pageUrl;
        }
        #endregion
        #region public static string GenerateCommentMailBody(PageReference pageLink, string name, string email, string comment)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pageLink"></param>
        /// <param name="name"></param>
        /// <param name="email"></param>
        /// <param name="comment"></param>
        /// <returns></returns>
        public static string GenerateCommentMailBody(PageReference pageLink, string name, string email, string comment) {

            var page = DataFactory.Instance.GetPage(pageLink);
            if (!string.IsNullOrEmpty(email))
                name += " <a href=\"mailto:" + email + "\">" + email + "</a>";

            var body = new StringBuilder();

            body.Append("<p>");
            body.Append(string.Format(LanguageManager.Instance.Translate("/municipality/units/comment/mailintro"), name));
            body.Append("</p>");
            body.Append("<p>");
            body.Append("<b>" + page.PageName + "</b>");
            body.Append("<br/>");
            body.Append(PathUtil.GetCurrentPath(SiteMap.RootNode.Title, " / ", true));
            body.Append("<br/>");

            if (!string.IsNullOrEmpty((string)page["MainIntro"])) {
                body.Append(page["MainIntro"]);
                body.Append("<br/>");
            }

            //Add read link
            body.Append("<a href=\"");
            body.Append(GeneratePageUrl(page));
            body.Append("\">");
            body.Append(LanguageManager.Instance.Translate("/municipality/units/comment/readlink"));
            body.Append("</a>");
            body.Append("</p>");

            body.Append("<p>");
            body.Append("<b>" + LanguageManager.Instance.Translate("/municipality/units/comment/comment") + "</b><br/>");
            body.Append(comment);

            body.Append("</p></body></html>");

            return body.ToString();
        }
        #endregion
        #region public string SendComment(int id, string name, string email, string comment)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="email"></param>
        /// <param name="comment"></param>
        /// <returns></returns>
        public static string SendComment(int id, string name, string email, string comment) {
            try {
                var pageLink = new PageReference(id);
                SendHtmlMail(LanguageManager.Instance.Translate("/municipality/units/comment/subject"), GenerateCommentMailBody(pageLink, name, email, comment), SiteSettings.Instance.WebmasterEmail, SiteSettings.Instance.SystemEmail);
                return "<div id=\"comment-form-message\" class=\"systeminfo\"><div><strong>" + LanguageManager.Instance.Translate("/municipality/units/comment/sentmessage") + "</strong></div></div>";
            } catch (Exception ex) {
                return "<div id=\"comment-form-message\" class=\"systemwarning\"><div><strong>" + LanguageManager.Instance.Translate("/municipality/global/systemerror") + "</strong><p>" + ex.Message + "</p></div></div>";
            }
        }
        #endregion
        /* *******************************************************************
        *  Private methods 
        * *******************************************************************/
        #region private static void AddHtmlMailHeader(string mailCss, string subject, StringBuilder body)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        private static void AddHtmlMailHeader(string subject, StringBuilder body) {
            body.Append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
            body.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"sv\" lang=\"sv\">");
            body.Append("<head>");
            body.Append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></meta>");
            body.Append("<title>");
            body.Append(subject);
            body.Append("</title>");
            body.Append("</head>");
        }
        #endregion
    }
}